<template>
    <div id='index'>
        <div class="card-container">
            <el-row :gutter="10">
            <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
                <el-col :span="20" :offset="0">
                    <el-form-item label="名称" prop="eewId">
                        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                </el-col>
                <el-col :span="4" :offset="0">
                    <el-form-item>
                        <el-button  icon="el-icon-search" size="mini" @click="handleQuery"
                            v-hasPermi="['levelConfig:list']">搜索
                        </el-button>
                        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
                    </el-form-item>
                </el-col>
            </el-form>
        </el-row>
        </div>
       
        <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button   icon="el-icon-plus" size="mini" v-hasPermi="['levelConfig:add']"
                    @click="handelAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button   icon="el-icon-delete" size="mini" :disabled="multiple"
                    v-hasPermi="['levelConfig:remove']" v-show="!multiple" @click="handleDelete">删除</el-button>
            </el-col>
        </el-row> -->
        <div class="card-container">
            <div class="body-title">
                <div class="body-title-right">
                    <el-button   icon="el-icon-plus" size="mini" v-hasPermi="['levelConfig:add']"
                    @click="handelAdd">新增</el-button>
                    <el-button   icon="el-icon-delete" size="mini" :disabled="multiple"
                    v-hasPermi="['levelConfig:remove']" v-show="!multiple" @click="handleDelete">删除</el-button>
                    <!-- <el-button  size="mini" @click="handelAdd" icon="el-icon-plus" v-hasPermi="['levelConfig:add']">新
                        增</el-button> -->

                    <!-- <el-button  size="mini" :disabled="multiple" v-show="!multiple"
                        @click="handleDelete">删除</el-button> -->

                </div>
            </div>
            <el-table v-loading="loading" height="550" :data="tableData" :row-key="tableData.length > 0 ? row => row.id : ''"
                :expand-row-keys="tableData.length > 0 ? [tableData[0].id] : []"
                @selection-change="handleSelectionChange" @expand-change="handleExpandChange">
                <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-table :data="scope.row.levelConfigVOList ? scope.row.levelConfigVOList : []"
                            style="width: 100%;">
                            <el-table-column prop="intensity" align="center" show-overflow-tooltip label="烈度范围"
                                min-width="150">
                                <template slot-scope="scope">
                                    <el-tag v-for="(item, index) in scope.row.intensity" :key="index"
                                        :color="formatColor(scope.row.level)" effect="dark">{{ item }}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="level" align="center" show-overflow-tooltip label="预警等级" min-width="80">
                            </el-table-column>
                            <el-table-column prop="levelColor" align="center" show-overflow-tooltip label="等级颜色"
                                min-width="80">
                            </el-table-column>
                            <el-table-column prop="guidance" align="center" show-overflow-tooltip label="避震指导"
                                min-width="80">
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column prop="name" align="center" show-overflow-tooltip label="名称" min-width="100">
                </el-table-column>
                <el-table-column prop="province" align="center" show-overflow-tooltip label="省份" min-width="100">
                </el-table-column>
                <el-table-column prop="defaultFlag" align="center" show-overflow-tooltip label="是否默认配置" min-width="100">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.defaultFlag == 1 ? 'success' : 'danger'">
                            {{ scope.row.defaultFlag == 1 ? '默认' : '非默认' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="100" label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleMessage(scope.row)"
                            v-hasPermi="['levelConfig:edit']">编辑</el-button>
                        <!-- <el-button type="text" @click="handleDelet(scope.row)"
                            v-hasPermi="['levelConfig:remove']">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" /> -->
        </div>
        <el-dialog :title="titles" :close-on-click-modal="false" :visible.sync="outerVisible" center>
            <div class="card-container">
                <el-input v-model="dialogData.name" placeholder="请输入名称">
            </el-input>
            <div class="dialog-boby" @click="handleSelect(item)" v-for="(item, index) in dialogData.levelConfigVOList "
                :key="index">
                <div class="lev-title">
                    <span :style="{ background: formatColor(item.level) }"></span>
                    <span>{{ item.levelColor }}</span>
                </div>
                <div class="lev-limits">
                    <span>烈度范围：</span>
                    <div>
                        <el-tag v-for="(tag, i) in item.intensity" :key="i" :color="formatColor(item.level)"
                            effect="dark">{{ tag
                            }}</el-tag>
                    </div>
                </div>

            </div>
            <div class="form">
                <span>是否默认配置：</span>
                <el-switch v-model="dialogData.defaultFlag" active-value="1" inactive-value="0">
                </el-switch>
            </div>
            <div class="form">
                <span>省份：</span>
                <el-select v-model="dialogData.province" :style="'width:400px'" placeholder="请选择省份">
                    <el-option v-for="(item, index) in provinceList" :key="index" :value="item">
                    </el-option>
                </el-select>
            </div>
            <!-- <el-form-item label="是否启用" prop="enable">
                    <el-switch v-model="form.enable" :disabled="switchLoad" :active-value="1" :inactive-value="0">
                    </el-switch>
                </el-form-item> -->
            <el-dialog :close-on-click-modal="false" width="30%" :title="selet_title" :visible.sync="innerVisible"
                append-to-body center>
                <boxselect v-model="value4" :options="options" @getData="getData"
                    :levelConfigVOList="dialogData.levelConfigVOList" />
                <!-- <div slot="footer" class="dialog-footer">
                    <el-button @click="handleSubmit" round>确定</el-button>
                </div> -->
            </el-dialog>
          
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleSubmitData" round>确定</el-button>
                <!-- <el-button  >打开内层 Dialog</el-button> -->
            </div>
        </el-dialog>
    </div>
</template>
  
<script>

import { listLevelWarm, updateWarm, addWarm, getLevelWarm, deletWarm, getProvinceList } from '@/api/configuration/alertLevel/index.js'
export default {
    components: {
        boxselect: () => import("./components/select.vue")
    },

    name: 'eventQuery',
    dicts: ['earthquake_level', 'event_type', 'sys_event_type', 'res_level1'],
    data() {
        return {
            options: [],
            value4: [],
            titles: '',
            msgId: '',
            provinceList: [],
            total: 1,
            multiple: true,
            dialogVisible: false,
            outerVisible: false,
            innerVisible: false,
            messageData: {},
            loading: true,
            tableData: [{ id: 0 }],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null
            },
            dialogData: [],
            _num: null,
            selet_title: '',
            names: []
        };
    },
    computed: {},
    created() {
        this.listLevelWarm()
        this.getProvinceList()
    },
    mounted() {

    },
    beforeCreate() { },
    beforeMount() { },
    methods: {
        formatColor(val) {
            switch (val) {
                case '无预警':
                    return 'grey'
                case 'Ⅳ级':
                    return '#409EFF'
                case 'Ⅲ级':
                    return 'yellow'
                case 'Ⅱ级':
                    return 'orange'
                case 'Ⅰ级':
                    return 'red'
                default:
                    break;
            }
        },
        async listLevelWarm() {
            this.loading = true
            const res = await listLevelWarm(this.queryParams);
            if (res.code == 200) {
                this.loading = false
                this.tableData = res.rows || [];
                this.tableData.forEach((item, index) => {
                    item.id = index
                    item.levelConfigVOList.forEach(list => {
                        if(list.intensity==''){
                            list.intensity = []
                        }else{
                            list.intensity = list.intensity.split(',').map(Number);
                        }
                        
                    })

                })
                console.log(this.tableData,'this.tableData')
            }
        },
        getData(val) {
            this.innerVisible = val.isshow
        },
        handelAdd() {
            console.log('add')
            this.titles = '新增'
            this.dialogData = {
                name: "",
                levelConfigVOList:
                    [
                        { id: 1, name: "", intensity: [0, 1, 2], level: "无预警", levelColor: "无预警（灰色）", guidance: "此次地震无影响" },
                        { id: 2, name: "", intensity: [3, 4, 5], level: "Ⅳ级", levelColor: "蓝色预警", guidance: "有感地震，注意观察" },
                        { id: 3, name: "", intensity: [6, 7, 8], level: "Ⅲ级", levelColor: "黄色预警", guidance: "有感地震，注意防范" },
                        { id: 4, name: "", intensity: [9, 10], level: "Ⅱ级", levelColor: "橙色预警", guidance: "强烈地震，立即避险" },
                        { id: 5, name: "", intensity: [11, 12], level: "Ⅰ级", levelColor: "红色预警", guidance: "破坏地震，紧急避险" }]
            }
            this.outerVisible = true
        },
        handleSelectionChange(selection) {
            this.names = selection.map((item) => item.name);
            this.multiple = !selection.length;
        },

        async getProvinceList() {
            const res = await getProvinceList()
            if (res.code == 200) {
                this.provinceList = res.data
            }
        },
        async handleDelete() {
            const res = await deletWarm(this.names);
            if (res.code == 200) {
                this.listLevelWarm()
                this.$modal.msgSuccess('删除成功')
            } else {
                this.$modal.msgError(msg)
            }
        },
        handleSubmitData() {
            // this.dialogData
            // console.log(this.dialogData,'this.dialogData')
            let isLength = this.isValidLength(this.dialogData.levelConfigVOList)
            let isValid = this.isValidSelection(this.dialogData.levelConfigVOList)
            if (isLength && isValid) {
                let obj = JSON.parse(JSON.stringify(this.dialogData))
                obj.levelConfigVOList.forEach(item => {
                    item.intensity = item.intensity.join(',')
                    item.name = obj.name
                })
                obj.levelConfigDTOList = obj.levelConfigVOList
                console.log(delete obj.levelConfigVOList, obj)
                if (this.dialogData.name && this.dialogData.province) {
                    if (this.titles == '编辑') {
                        this.updateWarm(obj)
                    } else {
                        this.addWarm(obj)
                    }
                } else {
                    if(this.dialogData.name){
                        this.$modal.msgError('省份不能为空')
                    }else{
                        this.$modal.msgError('名称不能为空')
                    }
                   
                }
            } else {
                isLength ? this.$modal.msgError('等级选择有误，请检查等级') : this.$modal.msgError('等级有缺漏，请检查选择等级')
            }


        },

        async getLevelWarm() {
            this.laoding = true
            const res = await getLevelWarm(this.queryParams.name);
            if (res.code == 200) {
                this.tableData = res.data;
                this.tableData.forEach(item => {
                    item.levelConfigVOList.forEach(list => {
                        list.intensity = list.intensity.split(',').map(Number);
                    })
                })
                this.total = res.total;
                this.laoding = false
            } else {
                this.$modal.msgError(msg)
            }
        },

        async addWarm(obj) {
            const res = await addWarm(obj);
            if (res.code == 200) {
                this.outerVisible = false
                this.$modal.msgSuccess('新增成功')
                this.listLevelWarm()
            } else {
                this.$modal.msgError(msg)
            }
        },

        async updateWarm(obj) {
            const res = await updateWarm(obj);
            if (res.code == 200) {
                this.outerVisible = false
                this.$modal.msgSuccess('修改成功')
                this.listLevelWarm()
            } else {
                this.$modal.msgError(msg)
            }
        },
        handleSelect(val) {
            console.log(val, 'val')
            this.options.push()
            this.selet_title = val.levelColor
            this.options = val.intensity
            this.innerVisible = true
        },
        handleSubmit() {
            let isValid = this.isValidSelection(this.dialogData.levelConfigVOList)
            if (isValid) {
                this.innerVisible = false
                this.dialogData.levelConfigVOList.forEach(item => {
                    if (item.intensity != this.options) {
                        item.intensity = this.removeRepeat(item.intensity, this.options)
                    }
                })
            } else {
                console.log('err')
                this.$modal.msgError('所选等级必须连续，不可跳选');
            }
        },
        handleMessage(val) {
            console.log('编辑', val)
            this.titles = '编辑'
            this.dialogData = JSON.parse(JSON.stringify(val))
            this.outerVisible = true
        },
        handleQuery() {
            console.log('搜索')
            this.listLevelWarm()
        },
        handleExpandChange() {
            console.log("handleExpandChange")
        },
        removeRepeat(rawArr, removeArr) {
            let raw = new Set([...rawArr])
            for (let i of removeArr) {
                raw.delete(i)
            }
            return [...raw]
        },
        isValidSelection(selectedRegions) {
            // 检查每个区域内数字是否递增
            for (let i = 0; i < selectedRegions.length; i++) {
                const region = selectedRegions[i].intensity;
                if (region.length > 0) {
                    for (let j = 1; j < region.length; j++) {
                        if (region[j] != region[j - 1] + 1) {
                            return false;
                        }
                    }
                }
            }
            return true;
        },
        isValidLength(arr) {
            let _arr = []
            // 检查每个区域内数字是否递增
            for (let i = 0; i < arr.length; i++) {
                const region = arr[i].intensity;
                for (let j = 0; j < region.length; j++) {
                    _arr.push(region[j])
                }
            }
            console.log(_arr.length, _arr)
            if (_arr.length == 13) {
                return true
            } else {
                return false
            }
        }
    },
};
</script>
<style lang='scss' scoped>
#index {
    width: 100%;
    height: 100%;
    padding: 20px;
}


.body-title {
    margin-bottom: 10px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}


::v-deep .el-table__expanded-cell,
.dialog-boby {
    .el-tag--medium {
        width: 40px;
        height: 28px;
        line-height: 28px;
        margin-right: 10px;
        text-align: center;
        border: none;
        color: #000;
    }
}

.level {
    display: flex;
    align-items: center;
    min-width: 504px;
}

::v-deep .el-card {
    border-radius: 12px;
}

::v-deep .el-dialog {
    background: #111113;

    .el-input__inner {
        background-color: #25333d;
        color: #fff;
    }

    .el-button {
        color: #fff;
    }
}

::v-deep .el-dialog__title {
    color: #fff;
}


.dialog-boby {
    margin-top: 10px;
    background-color: #25333d;
    border-radius: 5px;
    padding: 10px;

    .lev-title {
        margin-bottom: 5px;
        display: flex;
        color: #fff;

        >span:nth-child(1) {
            margin-right: 10px;
            width: 30px;
            height: 20px;
            border-radius: 5px;
            // background-color: #000;
        }
    }

    .lev-limits {
        display: flex;
        font-size: 16px;
    }
}

.form {
    margin-top: 10px;
    padding: 10px;
    background-color: #25333d;
    color: #fff;
    border-radius: 4px;
}

::v-deep .el-button--medium.is-round {
    width: 100%;
    padding: 10px 20px;
    background-color: #25333d;
}

.bor {
    display: inline-block;
    width: 50px;
    height: 1px;
    margin: 0 10px;
    background: #dfe6ec;
}

::v-deep .jv-button {
    &::before {
        content: "复制";
    }
}
</style>